package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.dto.PaBalmOrderDto;
import cn.chinaflame.pagodas.dto.PaBlessDto;
import cn.chinaflame.pagodas.dto.PaBlessQryDto;
import cn.chinaflame.pagodas.entity.PaBalmOrder;
import cn.chinaflame.pagodas.entity.VwBlessDetail;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.PaBalmOrderRepository;
import cn.chinaflame.pagodas.repository.VwBlessDetailRepository;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;

/**
 * @author created by lbq
 * @date 2018年1月12日 下午8:46:46
 **/
@Service
public class PaBlessService {
    private final static Logger log = LoggerFactory.getLogger(PaBlessService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private VwBlessDetailRepository vwBlessDetailRepository;
    @Autowired
    private PaBalmOrderRepository paBalmOrderRepository;

    /**
     * 查询我的祝福列表
     *
     * @param sourceMemberId //根据会员id来查
     * @param sourceOpenid   //或者根据openid来查
     * @return
     */
    public List<PaBlessDto> query(String sourceMemberId, String sourceOpenid) {
        log.info("查询祝福列表sourceMemberId:{},sourceOpenid:{}", sourceMemberId, sourceOpenid);
        ParamPreconditions.checkArgument(!Strings.isNullOrEmpty(sourceMemberId) || !Strings.isNullOrEmpty(sourceOpenid),
                CodeEnum.FAIL.getCode(), "会员id和openid不能同时为空");
        String sql = null;
        if (!Strings.isNullOrEmpty(sourceMemberId))
            sql = " select b.target_member_id as targetMemberId,b.target_openid as targetOpenid, " +
                    " m.name as targetName,o.id as orderId,r.be_wished_name as beWishedName,r.be_wished_sex as beWishedSex, " +
                    " r.be_wished_birthday as beWishedBirthday,r.be_wished_address as beWishedAddress " +
                    " from pa_bless b,pa_member m,pa_order o, pa_orderitem r " +
                    " where b.source_member_id = m.id and b.order_id = o.id and r.order_id = o.id and b.source_member_id=" + sourceMemberId;
        else
            sql = " select b.target_member_id as targetMemberId,b.target_openid as targetOpenid, " +
                    " m.name as targetName,o.id as orderId,r.be_wished_name as beWishedName,r.be_wished_sex as beWishedSex, " +
                    " r.be_wished_birthday as beWishedBirthday,r.be_wished_address as beWishedAddress " +
                    " from pa_bless b,pa_member m,pa_order o, pa_orderitem r " +
                    " where b.source_member_id = m.id and b.order_id = o.id and r.order_id = o.id and b.source_openid=" + sourceOpenid;
        List<PaBlessDto> result = jdbcTemplate.queryForList(sql, PaBlessDto.class);
        return result;
    }

    /**
     * 我的供灯
     *
     * @param openid
     * @param memberId
     * @return
     */
    public List<Map<String, Object>> myLamp(String openid, String memberId) {
        log.info("查询我的供灯【service】openid:{},memberId:{}", openid, memberId);
        ParamPreconditions.checkArgument(!Strings.isNullOrEmpty(openid) || !Strings.isNullOrEmpty(memberId), CodeEnum.FAIL.getCode(), "openid或者会员id不能都为空值");
        String sql = "SELECT a.id as id , a.money as money,a.pay_status as payStatus,b.member_name as memberName,"
                + " b.area_id as areaId,b.position_id as positionId,b.number,b.start_time as startTime,b.end_time as endTime,c.name as productName "
                + " FROM pa_order a  "
                + " INNER  JOIN pa_orderitem b ON (a.id = b.order_id) "
                + " INNER  JOIN pa_product c ON (b.product_id = c.id) ";
        if (!Strings.isNullOrEmpty(openid)) {
            sql = sql + " WHERE a.openid=" + openid;
        } else {
            sql = sql + " where a.member_id=" + memberId;
        }
        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
        return result;
    }

    /**
     * 祝福详情
     *
     * @param id
     * @param memberId
     * @param openid
     * @param mobile
     * @return
     */
    public List<PaBlessQryDto> queryDetail(String id, String memberId, String openid, String mobile, String orderType) {
        log.info("查询祝福详情列表【service】id:{},memberId:{},openid:{},mobile:{},orderType:{}", id, memberId, openid, mobile, orderType);

        List<VwBlessDetail> entityList = vwBlessDetailRepository.findAll(new Specification<VwBlessDetail>() {

            @Override
            public Predicate toPredicate(Root<VwBlessDetail> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = Lists.newArrayList();
//				Predicate p1 = cb.equal(root.get("status").as(String.class), Sysconst.BLESS_STATUS_USING);
//				Predicate p2 = cb.equal(root.get("status").as(String.class), Sysconst.BLESS_STATUS_FINISH);
//				cb.or(p1,p2);
                if (!Strings.isNullOrEmpty(id))
                    list.add(cb.equal(root.get("id").as(String.class), id));
                if (!Strings.isNullOrEmpty(memberId))
                    list.add(cb.equal(root.get("sourceMemberId").as(String.class), memberId));
                if (!Strings.isNullOrEmpty(openid))
                    list.add(cb.equal(root.get("sourceOpenid").as(String.class), openid));
                if (!Strings.isNullOrEmpty(mobile))
                    list.add(cb.equal(root.get("sourceMemberMobile").as(String.class), mobile));
                if (!Strings.isNullOrEmpty(orderType))
                    list.add(cb.equal(root.get("orderType").as(String.class), orderType));
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        });
        List<PaBlessQryDto> dtos = Lists.newArrayList();
        
        for (int i = 0; i < entityList.size(); i++) {
            if (Sysconst.BLESS_STATUS_USING.equals(entityList.get(i).getStatus())
                    || Sysconst.BLESS_STATUS_INVALID.equals(entityList.get(i).getStatus())) {
            	List<PaBalmOrderDto> orderList = Lists.newArrayList();
                PaBlessQryDto dto = new PaBlessQryDto();
                BeanUtils.copyProperties(entityList.get(i), dto);
                String nowTime = DateTimes.nowDateTime();
                int wishStatus = 1;
                wishStatus = dto.getEndTime().compareTo(nowTime);
                dto.setWishStatus(wishStatus);
                dtos.add(dto);
                PaBalmOrder suborder = paBalmOrderRepository.findOne(entityList.get(i).getOrderId());
                if(suborder != null){
                	PaBalmOrderDto suborderDto = new PaBalmOrderDto();
                	BeanUtils.copyProperties(suborder, suborderDto);
                	orderList.add(suborderDto);
                }
                dto.setOrderList(orderList);
            }
        }
        return dtos;
    }
	
	
/*	public Object bless(){
		Map<String,List<Map<String, Object>>> result = new HashMap<String,List<Map<String, Object>>>();
		String sql="SELECT b.order_id,b.be_wished_name,b.be_wished_sex,b.be_wished_birthday,"
				+ " b.be_wished_mobile,b.be_wished_address,b.be_wished_memo from  pa_orderitem b "
				+ " LEFT JOIN pa_order c on(b.order_id=c.id ) WHERE c.pay_type='2' AND c.id IN (SELECT order_id   from pa_bless a)";
		List<Map<String, Object>> list= jdbcTemplate.queryForList(sql);
		result.put("list", list);
		return result;
	}*/
}
